<?php
/**
 * Created by IntelliJ IDEA.
 * User: luwei
 * Date: 2017/5/26
 * Time: 20:38
 */

namespace luweiss\alipay;


class Alipay
{
    public $appId;
    public $publicKey;
    public $privateKey;

    public $signType = 'RSA2';

    /**
     * 初始化
     *
     * @param array $args 初始化参数
     *
     * [
     *
     * 'appId' => '',
     *
     * 'publicKey' => '',
     *
     * 'privateKey' => '',
     *
     * ]
     * @return Alipay|null
     */
    public function __construct($args)
    {
        $this->appId = isset($args['appId']) ? $args['appId'] : null;
        $this->publicKey = isset($args['publicKey']) ? $args['publicKey'] : null;
        $this->privateKey = isset($args['privateKey']) ? $args['privateKey'] : null;
        return $this->init();
    }

    private function init()
    {
        return $this;
    }

    /**
     * 数据签名
     *
     * @param string $data 待签名内容
     * @return string
     */
    public function sign($data)
    {
        if ($this->signType == 'RSA2')
            openssl_sign($data, $sign, $this->privateKey, OPENSSL_ALGO_SHA256);
        else
            openssl_sign($data, $sign, $this->privateKey);
        $sign = base64_encode($sign);
        return $sign;
    }

    /**
     * 验证签名
     *
     * @param string $data 待签名内容
     * @return bool
     */
    public function verifySign($sign, $data)
    {
        if ($this->signType == 'RSA2')
            $res = (bool)openssl_verify($data, base64_decode($sign), $this->publicKey, OPENSSL_ALGO_SHA256);
        else
            $res = (bool)openssl_verify($data, base64_decode($sign), $this->publicKey);
        return $res;
    }
}